package com.cool.reggie.core.interceptor;

import com.cool.reggie.core.annotation.IgnoreResponseWrapper;
import com.cool.reggie.utils.ResultData;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @Author ifredom
 * @Date  2022/7/14
 * @ClassName  ResponseBodyWrapHandler
 * @Version  1.0.0
 * @Description 对 controller 层返回的数据做统一处理
**/
public class ResponseBodyWrapHandler implements HandlerMethodReturnValueHandler {
    private final HandlerMethodReturnValueHandler delegate;

    public ResponseBodyWrapHandler(HandlerMethodReturnValueHandler delegate) {
        this.delegate = delegate;
    }

    @Override
    public boolean supportsReturnType(@NotNull MethodParameter returnType) {
        return delegate.supportsReturnType(returnType);
    }

    @Override
    public void handleReturnValue(Object returnValue,
                                  MethodParameter returnType,
                                  @NotNull ModelAndViewContainer mavContainer,
                                  @NotNull NativeWebRequest webRequest) throws Exception {
        // 如果类或者方法含有不包装注解则忽略包装
        IgnoreResponseWrapper wrapper = returnType.getDeclaringClass().getAnnotation(IgnoreResponseWrapper.class);
        if (wrapper != null) {
            delegate.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
            return;
        }
        wrapper = returnType.getMethodAnnotation(IgnoreResponseWrapper.class);
        if (wrapper != null) {
            delegate.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
            return;
        }

        // 自定义返回格式
        ResultData responseBase = new ResultData(1,"success",returnValue);
        delegate.handleReturnValue(responseBase, returnType, mavContainer, webRequest);
    }
}
